package com.ssy.lingxi.platform.template.service.serviceimpl.web;

import cn.hutool.core.collection.CollectionUtil;
import com.ssy.lingxi.common.constant.member.MemberTypeEnum;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberInnerControllerFeign;
import com.ssy.lingxi.member.merchant.api.feign.inner.MemberLevelRightCreditControllerFeign;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignIdVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignLrcVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.MemberFeignRegisterQueryVO;
import com.ssy.lingxi.platform.manage.api.feign.inner.AreaControllerFeign;
import com.ssy.lingxi.platform.template.service.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.template.service.constant.SeoDoorTypeEnum;
import com.ssy.lingxi.platform.template.service.constant.SeoTypeEnum;
import com.ssy.lingxi.platform.template.service.entity.door.MemberSelf;
import com.ssy.lingxi.platform.template.service.entity.door.Seo;
import com.ssy.lingxi.platform.template.service.model.bo.AreaBO;
import com.ssy.lingxi.platform.template.service.model.dto.common.MemberIdDTO;
import com.ssy.lingxi.platform.template.service.model.dto.web.SaveSelfDTO;
import com.ssy.lingxi.platform.template.service.model.vo.web.MemberSelfMainVO;
import com.ssy.lingxi.platform.template.service.repository.MemberSelfRepository;
import com.ssy.lingxi.platform.template.service.repository.SeoRepository;
import com.ssy.lingxi.platform.template.service.service.web.MemberSelfWebService;
import com.ssy.lingxi.product.api.feign.ICommodityFeign;
import com.ssy.lingxi.product.api.model.request.MemberRequest;
import com.ssy.lingxi.product.api.model.response.store.StoreResponse;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

/**
 * @menu web - 会员自营门户 - 业务实现层
 * @author fhj
 * @version 2.0.0
 * @date 2021/10/18
 */
@Slf4j
@Service
public class MemberSelfWebServiceImpl implements MemberSelfWebService {

    @Resource
    private MemberSelfRepository memberSelfRepository;
    @Resource
    private MemberLevelRightCreditControllerFeign memberLevelRightCreditControllerFeign;
    @Resource
    private MemberInnerControllerFeign memberInnerControllerFeign;
    @Resource
    private AreaControllerFeign areaControllerFeign;
    @Resource
    private ICommodityFeign commodityFeign;
    @Resource
    private SeoRepository seoRepository;

    @Override
    @ApiOperation(value = "保存当前登录会员的自营门户")
    public Wrapper<Void> saveCurrMemberSelf(SaveSelfDTO dto, UserLoginCacheDTO user) {
        //校验（只有是服务提供者且企业类型是企业会员或个人会员才能创建自营门户, 一个会员只能有一个自营门户。
        if(!user.getMemberRoleType().equals(RoleTypeEnum.SERVICE_PROVIDER.getCode())) {
            return Wrapper.fail("角色类型不是服务提供者, 不能创建自营门户");
        }
        if(!(user.getMemberType().equals(MemberTypeEnum.MERCHANT.getCode()) || user.getMemberType().equals(MemberTypeEnum.MERCHANT_PERSONAL.getCode()))) {
            return Wrapper.fail("会员类型不是企业会员或个人会员, 不能创建自营门户");
        }

        //默认省、市编码都为0（所有/所有）
        List<String> provinceCodes = Stream.of("0").collect(toList());
        List<String> cityCodes = Stream.of("0").collect(toList());
        if(dto.getMemberShopAreas().stream().noneMatch(a -> a.getProvinceCode().equals("0"))) {
            provinceCodes = dto.getMemberShopAreas().stream().map(AreaBO::getProvinceCode).collect(Collectors.toList());
            cityCodes = dto.getMemberShopAreas().stream().filter(a -> !a.getCityCode().equals("0")).map(AreaBO::getCityCode).collect(Collectors.toList());

            List<String> feignCodes = dto.getMemberShopAreas().stream().filter(a -> a.getCityCode().equals("0")).map(AreaBO::getProvinceCode).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(feignCodes)) {
                Wrapper<List<String>> cityCodesWrapper = areaControllerFeign.findCityCodeByProvinceCode(feignCodes);
                if(cityCodesWrapper.getCode() == ResponseCode.SUCCESS.getCode() && CollectionUtil.isNotEmpty(cityCodesWrapper.getData())) {
                    cityCodes.addAll(cityCodesWrapper.getData());
                }
            }
        }

        //调用会员服务 -> 根据会员ID和角色ID获取平台会员的等级、注册年数、信用积分
        MemberFeignVO memberFeignVO = new MemberFeignVO();
        memberFeignVO.setMemberId(user.getMemberId());
        memberFeignVO.setRoleId(user.getMemberRoleId());
        Wrapper<MemberFeignLrcVO> platformMemberLrcWrapper = memberLevelRightCreditControllerFeign.getPlatformMemberLrc(memberFeignVO);
        if(platformMemberLrcWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("调用会员服务失败：{}", platformMemberLrcWrapper.getMessage());
            return Wrapper.fail(ResponseCode.SERVICE_MERCHANT_MEMBER_ERROR);
        }
        //调用会员服务 -> 根据会员Id查询会员注册信息
        MemberFeignIdVO memberFeignIdVO = new MemberFeignIdVO();
        memberFeignIdVO.setMemberId(user.getMemberId());
        Wrapper<MemberFeignRegisterQueryVO> memberRegisterInfoWrapper = memberInnerControllerFeign.getMemberRegisterInfo(memberFeignIdVO);
        if(memberRegisterInfoWrapper.getCode() != ResponseCode.SUCCESS.getCode()) {
            log.error("调用会员服务失败：{}", memberRegisterInfoWrapper.getMessage());
        }

        //保存会员自营门户
        MemberSelf memberSelf = memberSelfRepository.findByMemberId(user.getMemberId());
        memberSelf = memberSelf != null ? memberSelf : new MemberSelf();
        memberSelf.setMemberId(user.getMemberId());
        memberSelf.setRoleId(user.getMemberRoleId());
        memberSelf.setMemberShopAreas(dto.getMemberShopAreas());
        memberSelf.setDescribe(dto.getDescribe());
        memberSelf.setWorkshopPics(dto.getWorkshopPics());
        memberSelf.setHonorPics(dto.getHonorPics());
        memberSelf.setAlbumName(dto.getAlbumName());
        memberSelf.setAlbumUrl(dto.getAlbumUrl());
        memberSelf.setShopId(dto.getShopId());
        memberSelf.setUrl(dto.getUrl());
        memberSelf.setPhone(dto.getPhone());
        memberSelf.setAddress(dto.getAddress());
        memberSelf.setAreas(dto.getMemberShopAreas().stream().map(a -> a.getProvince() + "/" + a.getCity()).collect(Collectors.joining("，")));
        memberSelf.setProvincesCodeList(String.join("，", provinceCodes));
        memberSelf.setCityCodeList(String.join("，", cityCodes));
        memberSelf.setMemberName(user.getCompany());
        memberSelf.setLevelTag(platformMemberLrcWrapper.getData().getLevelTag());
        memberSelf.setRegisterYears(platformMemberLrcWrapper.getData().getRegisterYears());
        memberSelf.setCreditPoint(platformMemberLrcWrapper.getData().getCreditPoint());
        memberSelf.setRegisteredCapital(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getRegisteredCapital() : null);
        memberSelf.setEstablishmentDate(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getEstablishmentDate() : null);
        memberSelf.setBusinessLicence(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getBusinessLicence() : null);
        memberSelf.setRegisterArea(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getRegisterArea() : null);
        memberSelf.setRegisterAddress(memberRegisterInfoWrapper.getData() != null ? memberRegisterInfoWrapper.getData().getRegisterAddress() : null);
        memberSelfRepository.saveAndFlush(memberSelf);

        return Wrapper.success();
    }

    @Override
    @ApiOperation(value = "获取当前登录会员的自营门户")
    public Wrapper<MemberSelf> findCurrMemberSelf(UserLoginCacheDTO user) {
        return Wrapper.success(memberSelfRepository.findByMemberId(user.getMemberId()));
    }

    @Override
    public Wrapper<MemberSelfMainVO> memberSelfMain(MemberIdDTO dto) {
        //根据会员ID获取自营门户
        MemberSelf memberSelf = memberSelfRepository.findByMemberId(dto.getMemberId());
        if(memberSelf == null) {
            return Wrapper.fail("找不到会员自营门户");
        }

        //拷贝
        MemberSelfMainVO memberSelfMainVO = new MemberSelfMainVO();
        BeanUtils.copyProperties(memberSelf, memberSelfMainVO);

        //调用商品服务 -> 根据会员ID和角色ID集合获取自营门户的主营分类
        MemberRequest memberRequest = new MemberRequest();
        memberRequest.setMemberId(memberSelf.getMemberId());
        memberRequest.setMemberRoleId(memberSelf.getRoleId());
        Map<String, StoreResponse> map = commodityFeign.getCommodityAndCategoryByMemberIdAndMemberRoleId(
                Stream.of(memberRequest).collect(toList())
        );
        if(CollectionUtil.isNotEmpty(map) && map.get(memberSelfMainVO.getMemberId()+"-"+memberSelfMainVO.getRoleId()) != null) {
            memberSelfMainVO.setCustomerCategoryName(map.get(memberSelfMainVO.getMemberId()+"-"+memberSelfMainVO.getRoleId()).getCustomerCategoryName());
        }

        //获取自营门户SEO
        List<Seo> seoList = seoRepository.findAllByDoorTypeAndDoorIdAndStatus(
                SeoDoorTypeEnum.SELF.getCode(),
                memberSelf.getId(),
                CommonBooleanEnum.YES.getCode()
        );
        //封装自营门户SEO(首页、关于我们、行情资讯)
        if(CollectionUtil.isNotEmpty(seoList)) {
            Seo homePage = seoList.stream().filter(a -> a.getType().equals(SeoTypeEnum.HOME_PAGE.getCode())).findFirst().orElse(null);
            Seo aboutUs = seoList.stream().filter(a -> a.getType().equals(SeoTypeEnum.ABOUT_US.getCode())).findFirst().orElse(null);
            Seo informationUs = seoList.stream().filter(a -> a.getType().equals(SeoTypeEnum.INFORMATION_US.getCode())).findFirst().orElse(null);
            memberSelfMainVO.setHomePage(homePage);
            memberSelfMainVO.setAboutUs(aboutUs);
            memberSelfMainVO.setInformationUs(informationUs);
        }

        return Wrapper.success(memberSelfMainVO);
    }
}
